import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus/es'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: () => import('@/views/LoginPage.vue') },
        {
            path: '/index', component: () => import('@/views/LayOut.vue'), redirect: '/users',
            children: [
                { path: '/users', component: () => import('@/views/UserControl.vue') },
                { path: '/rights', component: () => import('@/views/LimitControl.vue') },
                { path: '/roles', component: () => import('@/views/RoleControl.vue') },
                { path: '/goods', component: () => import('@/views/GoodsControl.vue') },
                { path: '/params/:id?', component: () => import('@/views/ParamsControl.vue') },
                { path: '/categories', component: () => import('@/views/CategoriesControl.vue') },
                { path: '/orders', component: () => import('@/views/OrderControl.vue') },
                { path: '/reports', component: () => import('@/views/ReportControl.vue') }
            ]
        }
    ]
})

router.beforeEach(to => {
    if (to.path !== '/login' && !useUserStore().user.token) {
        ElMessage.error('请先登录')
        return '/login'
    }
})

export default router
